package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.service.*;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.ShiroUtils;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


@Service
public class TodoTaskServiceImpl implements ITodoTaskService {
    @Autowired
    private TaskService taskService;
    @Autowired
    private IProcessDifinitionService processDifinitionService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    @Autowired
    private IServiceItemService serviceItemService;

    @Override
    public TableDataInfo selectTodoList(CarPackageAudit carPackageAudit) {
        //需求，展示当前用户的任务列表（审核列表）
        long count = processDifinitionService.getCountBydefinitionKey(CarPackageAudit.DEFINITION_KEY, ShiroUtils.getUserId().toString());
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(0);
        tableDataInfo.setTotal(count);
        if(count==0) {
            return tableDataInfo;
        }
        //封装分页参数
        PageDomain pageDomain = TableSupport.getPageDomain();
        int startIndex = (pageDomain.getPageNum()-1)*pageDomain.getPageSize();

        List<CarPackageAudit> result = new ArrayList<>();
        //1.查询制定流程（流程定义key）和用户id，查询该用户在流程下所有需要处理的任务=》任务列表 List<Task>
        List<Task> taskList = processDifinitionService.getTaskByDifinitionKeyAndUserId(
                CarPackageAudit.DEFINITION_KEY,
                ShiroUtils.getUserId().toString(),
                startIndex,
                pageDomain.getPageSize());
        //2.遍历任务列表，获取每一个任务对应的流程实例，通过流程实例获取到businessKey =>CarPackageAudit.id
        for (Task task : taskList) {
            ProcessInstance instance = processDifinitionService.getInstanceById(task.getProcessInstanceId());
            String businessKey = instance.getBusinessKey();
            //3.基于businessKey获取审核对象
            CarPackageAudit audit = carPackageAuditService.selectCarPackageAuditById(Long.parseLong(businessKey));
            // 4.为审核对象设置当前任务id和任务名称
            audit.setTaskId(task.getId());
            audit.setTaskName(task.getName());
            result.add(audit);
        }
        tableDataInfo.setRows(result);
        return tableDataInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void taskAudit(String taskId, boolean auditStatus, String comment) {
        //一.任务相关（查找任务，接受任务，添加批注，完成任务，候选人设置）
        Task task = processDifinitionService.getTaskById(taskId);
        ProcessInstance instance = processDifinitionService.getInstanceById(task.getProcessInstanceId());

        Long businessKey = Long.parseLong(instance.getBusinessKey());
        processDifinitionService.claimAndComment(task,auditStatus,comment);
        //二.获取下一个节点
        List<Task> nextTaskList = processDifinitionService.getTaskByInstanceId(instance.getId());
        //三.如果有节点
        CarPackageAudit carPackageAudit = carPackageAuditService.selectCarPackageAuditById(businessKey);
        if(!CollectionUtils.isEmpty(nextTaskList)) {
            Task nextTask = nextTaskList.get(0);
            if(auditStatus) {
                //3.1如果同意审批
                //3.1.2根据当前节点key查找候选人
                List<SysUser> sysUsers = definitionNodeService.selectAuditorsByNodeKey(nextTask.getTaskDefinitionKey());
                List<String> auditNames = new ArrayList<>();
                //3.1.3为任务添加候选人
                for (SysUser sysUser : sysUsers) {
                    auditNames.add(sysUser.getUserName());
                    processDifinitionService.setTaskCandidateUser(nextTask.getId(),sysUser.getUserId().toString());
                }
                //3.1.4更新审核人状态中审核人字段
                carPackageAudit.setAuditors(JSON.toJSONString(auditNames));
            } else {
                //3.2不同意
                //3.2.1将人物候选人修改为任务发起人
                carPackageAudit.setAuditors(carPackageAudit.getCreateByName());
                processDifinitionService.setTaskCandidateUser(nextTask.getId(),carPackageAudit.getCreateBy());

                //3.2.2将任务对象状态修改为审核拒绝
                carPackageAudit.setStatus(CarPackageAudit.STATUS_REJECT);
            }

        } else {
            //四.没有节点（审核通过）
            //更新审核人，审核状态
            carPackageAudit.setStatus(CarPackageAudit.STATUS_PASS);
            carPackageAudit.setAuditors("");
            //更新服务项状态为审核通过
            ServiceItem serviceItem = carPackageAudit.getServiceItem();
            serviceItemService.updateStatus(serviceItem.getId(),ServiceItem.AUDITSTATUS_AUDITING,ServiceItem.AUDITSTATUS_APPROVED);
        }

        //审核记录对象的更新
        carPackageAuditService.updateCarPackageAudit(carPackageAudit);



    }

    @Override
    public void updateServiceItem(ServiceItem serviceItem, Long carPackageAuditId) {
        //修改服务项
        serviceItemService.updateAuditingServiceItem(serviceItem);
        //修改审核记录中的服务项
        CarPackageAudit carPackageAudit = new CarPackageAudit();
        carPackageAudit.setId(carPackageAuditId);
        carPackageAudit.setServiceItemInfo(JSON.toJSONString(serviceItem));
        carPackageAuditService.updateCarPackageAudit(carPackageAudit);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void reApply(Long carPackageAuditId, String taskId) {
        CarPackageAudit carPackageAudit = carPackageAuditService.selectCarPackageAuditById(carPackageAuditId);
        //1.获取任务对象
//        Task task = processDifinitionService.getTaskById(taskId);
//        //2.添加批注
//        processDifinitionService.addTaskComment(taskId,task.getProcessInstanceId(),carPackageAudit.getCreateByName()+"重新申请审核");
//        //3.覆盖流程变量
        ServiceItem serviceItem = carPackageAudit.getServiceItem();
        BigDecimal discountPrice = serviceItem.getDiscountPrice();

        Map<String,Object> map = new HashMap<>();
        map.put("money",discountPrice.doubleValue());
        //4.完成任务(添加批注，，覆盖变量，完成任务)
        processDifinitionService.claimAndComment(taskId,map,carPackageAudit.getCreateByName()+"重新申请审核");
        //5.获取下一个任务
        List<Task> taskList = processDifinitionService.getTaskByInstanceId(carPackageAudit.getInstanceId());
        if(!CollectionUtils.isEmpty(taskList)) {
            Task task = taskList.get(0);
            //6.为下一个任务设置候选人
            List<SysUser> auditors = definitionNodeService.selectAuditorsByNodeKey(task.getTaskDefinitionKey());
            List<String> auditorNames = new ArrayList<>();
            for (SysUser auditor : auditors) {
                processDifinitionService.setTaskCandidateUser(task.getId(),auditor.getUserId().toString());
                auditorNames.add(auditor.getUserName());
            }
            //7.修改审核记录的状态和审核人
            carPackageAudit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
            carPackageAudit.setAuditors(JSON.toJSONString(auditorNames));
            carPackageAuditService.updateCarPackageAudit(carPackageAudit);
        }

    }
}
